package com.ftar.urgent.adapter;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.ftar.urgent.R;
import com.ftar.urgent.api.resp.GetIndustryTreeResp;
import com.ftar.urgent.databinding.CatalogListItemBinding;
import com.rokid.utils.StringUtils;

import java.util.List;

public class CatalogAdapter extends BaseAdapter {
    private String TAG = this.getClass().getSimpleName();
    private Context mContext;
    private List<GetIndustryTreeResp> list;
    private int mSelectedId = 0;
    public CatalogAdapter(Context context, List<GetIndustryTreeResp> list) {
        this.mContext = context;
        this.list = list;
    }

    public int getmSelectedId() {
        return mSelectedId;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public GetIndustryTreeResp getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void refreshList(List<GetIndustryTreeResp> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CatalogListItemBinding itemBinding;
        if (convertView == null) {
            //创建一个databinding
            itemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.catalog_list_item, parent, false);

            //获取convertView
            convertView = itemBinding.getRoot();
        } else {
            //去除convertView中bangding的dataBinding
            itemBinding = DataBindingUtil.getBinding(convertView);
        }

        itemBinding.tvNumber.setText(String.valueOf(position + 1));
        GetIndustryTreeResp getIndustryTreeResp = list.get(position);
        String name = getIndustryTreeResp.getName();
        itemBinding.name.setText(name);

        String imgUrl = getIndustryTreeResp.getUrl();
        if (StringUtils.isNullOrEmpty(imgUrl)){
            imgUrl = "file:///android_asset/image/baozha.png";
        }
        Uri imgUri = Uri.parse(imgUrl);
        Glide.with(mContext).load(imgUri).into(itemBinding.img);
        Log.d(TAG, "mSelectedId:" + mSelectedId + "  position: " + position);
        itemBinding.name.setTextColor(mSelectedId == position ? mContext.getColor(R.color.orange) : mContext.getColor(R.color.white));

        return convertView;
    }

    public void setSelectItem(int pos) {
        mSelectedId = pos;
        this.notifyDataSetChanged();
    }

    public void setList(List<GetIndustryTreeResp> list) {
        this.list = list;
    }

    public List<GetIndustryTreeResp> getList() {
        return list;
    }
}
